package com.lanhe.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lanhe.common.constant.Constants;
import com.lanhe.common.constant.HttpStatus;
import com.lanhe.common.core.domain.entity.LhMemberBase;
import com.lanhe.common.exception.ServiceException;
import com.lanhe.common.utils.DateUtils;
import com.lanhe.common.utils.StringUtils;
import com.lanhe.common.utils.haoka.HaokaUtil;
import com.lanhe.common.utils.haoka.dto.OrdersHaokaApplyDto;
import com.lanhe.common.utils.haoka.dto.OrdersHaokaApplyNoticeDto;
import com.lanhe.common.utils.haoka.vo.HaokaApplyVO;
import com.lanhe.member.service.ILhMemberBaseService;
import com.lanhe.order.domain.LhOrdersHaoka;
import com.lanhe.order.domain.LhOrdersHaokaLog;
import com.lanhe.order.domain.LhOrdersPool;
import com.lanhe.order.domain.dto.LhOrdersHaokaApplyDto;
import com.lanhe.order.mapper.LhOrdersHaokaMapper;
import com.lanhe.order.service.ILhOrdersHaokaLogService;
import com.lanhe.order.service.ILhOrdersHaokaService;
import com.lanhe.order.service.ILhOrdersPoolService;
import com.lanhe.product.domain.LhHaokaProduct;
import com.lanhe.product.service.ILhHaokaProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.*;

/**
 * 号卡订单表(LhOrdersHaoka)表服务实现类
 *
 * @author zhanggl
 * @since 2023-12-25 20:19:30
 */
@Service
public class LhOrdersHaokaServiceImpl extends ServiceImpl<LhOrdersHaokaMapper, LhOrdersHaoka> implements ILhOrdersHaokaService {

	@Autowired
	private LhOrdersHaokaMapper ordersHaokaMapper;

	@Autowired
	private ILhHaokaProductService haokaProductService;


	@Autowired
	private ILhOrdersHaokaLogService ordersHaokaLogService;

	@Autowired
	private ILhMemberBaseService memberBaseService;


	@Autowired
	private ILhOrdersPoolService ordersPoolService;


	@Autowired
	private HaokaUtil haokaUtil;

	private final PlatformTransactionManager transactionManager;

	@Autowired
	public LhOrdersHaokaServiceImpl(PlatformTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

	/**
	 * 订单列表
	 *
	 * @param ordersHaoka 实体
	 * @return java.util.List<com.lanhe.order.domain.LhOrdersHaoka>
	 * @author zhanggl
	 * @date 2023/12/25
	 */
	@Override
	public List<LhOrdersHaoka> selectOrdersList(LhOrdersHaoka ordersHaoka) {
		LambdaQueryWrapper<LhOrdersHaoka> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(ObjectUtil.isNotNull(ordersHaoka.getMemberId()), LhOrdersHaoka::getMemberId, ordersHaoka.getMemberId());
		queryWrapper.eq(ObjectUtil.isNotNull(ordersHaoka.getStatus()), LhOrdersHaoka::getStatus, ordersHaoka.getStatus());
		queryWrapper.eq(ObjectUtil.isNotNull(ordersHaoka.getAuditStatus()), LhOrdersHaoka::getAuditStatus, ordersHaoka.getAuditStatus());
		queryWrapper.like(StringUtils.isNotBlank(ordersHaoka.getProductName()), LhOrdersHaoka::getProductName, ordersHaoka.getProductName());
		queryWrapper.eq(StringUtils.isNotBlank(ordersHaoka.getIsActivated()), LhOrdersHaoka::getIsActivated, ordersHaoka.getIsActivated());
		queryWrapper.eq(StringUtils.isNotBlank(ordersHaoka.getIsRecharged()), LhOrdersHaoka::getIsRecharged, ordersHaoka.getIsRecharged());
		queryWrapper.eq(StringUtils.isNotBlank(ordersHaoka.getOrderNumber()), LhOrdersHaoka::getOrderNumber, ordersHaoka.getOrderNumber());
		queryWrapper.ge(ObjectUtil.isNotNull(ordersHaoka.getBeginTime()), LhOrdersHaoka::getCreateTime, ordersHaoka.getBeginTime());
		queryWrapper.le(ObjectUtil.isNotNull(ordersHaoka.getEndTime()), LhOrdersHaoka::getCreateTime, ordersHaoka.getEndTime());
		queryWrapper.orderByDesc(LhOrdersHaoka::getOrderId);
		return ordersHaokaMapper.selectList(queryWrapper);
	}

	/**
	 * 敢探号提单V2
	 *
	 * @param applyDto DTO
	 * @return int
	 * @author zhanggl
	 * @date 2023/12/25
	 */
	@Override
	public int insertOrdersHaoka(LhOrdersHaokaApplyDto applyDto) {

		LhMemberBase user = memberBaseService.getUserByUserKey(applyDto.getUserKey());
		if (ObjectUtil.isNull(user)) {
			throw new ServiceException("查询异常，用户数据不存在", HttpStatus.ERROR);
		}

		// 获取产品详情
		LhHaokaProduct lhHaokaProduct = haokaProductService.selectHaokaProductById(applyDto.getProductId());
		if (ObjectUtil.isNull(lhHaokaProduct)) {
			throw new ServiceException("查询异常，数据不存在", HttpStatus.ERROR);
		}

		try {

			LhOrdersHaoka orders = new LhOrdersHaoka();

			// 生成订单号
			String orderNumber = DateUtils.generateOrderCode();
			orders.setOrderNumber(orderNumber);
			orders.setProductId(lhHaokaProduct.getProductId());
			orders.setProductName(lhHaokaProduct.getProductName());
			orders.setProductLog(lhHaokaProduct.getProductLogo());
			orders.setMemberId(user.getMemberId());
			orders.setIdName(applyDto.getIdName());
			orders.setIdNum(applyDto.getIdNum());
			orders.setMobile(applyDto.getMobile());
			orders.setName(applyDto.getName());
			orders.setProvinceCode(applyDto.getProvinceCode());
			orders.setProvince(applyDto.getProvince());
			orders.setCityCode(applyDto.getCityCode());
			orders.setCity(applyDto.getCity());
			orders.setDistrictCode(applyDto.getDistrictCode());
			orders.setDistrict(applyDto.getDistrict());
			orders.setAddress(applyDto.getAddress());
			orders.setProfit(lhHaokaProduct.getExpectIncome());
			orders.setCreateTime(new Date());

			// 拷贝
			OrdersHaokaApplyDto haokaApplyDto = new OrdersHaokaApplyDto();
			BeanUtil.copyProperties(applyDto, haokaApplyDto);
			haokaApplyDto.setSourceId(orderNumber);
			haokaApplyDto.setSku(lhHaokaProduct.getSku());

			// 提单
			String resource = haokaUtil.purchaseApply(haokaApplyDto);
			HaokaApplyVO haokaApplyVO = JSONObject.parseObject(resource, HaokaApplyVO.class);
			if (!Constants.GeneralIntType.ZERO.equals(haokaApplyVO.getMsg().getCode())) {
				throw new ServiceException("提单失败->" + haokaApplyVO.getMsg().getInfo(), HttpStatus.ERROR);
			}
			orders.setOrderHaokaId(haokaApplyVO.getData().getId());
			orders.setStatus(haokaApplyVO.getData().getStatus());
			orders.setStrRand(haokaApplyVO.getData().getStr_rand());
			ordersHaokaMapper.insert(orders);
			return orders.getOrderId().intValue();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 敢探号提单-回调通知
	 *
	 * @param params 实体对象
	 */
	@Override
	public void purchaseNotice(OrdersHaokaApplyNoticeDto params) {

		// 插入回调日志
		LhOrdersHaokaLog lhOrdersHaokaLog = new LhOrdersHaokaLog();
		lhOrdersHaokaLog.setOuterId(params.getOuter_id());
		lhOrdersHaokaLog.setPlanMobileProduced(params.getPlan_mobile_produced());
		lhOrdersHaokaLog.setState(params.getStatus());
		lhOrdersHaokaLog.setSign(params.getSign());
		lhOrdersHaokaLog.setIsActivated(params.getIs_activated());
		lhOrdersHaokaLog.setActivatedAt(params.getActivated_at());
		lhOrdersHaokaLog.setIsRecharged(params.getIs_recharged());
		lhOrdersHaokaLog.setRechargedAt(params.getRecharged_at());
		lhOrdersHaokaLog.setTrackingCompany(params.getTracking_company());
		lhOrdersHaokaLog.setTrackingNumber(params.getTracking_number());
		lhOrdersHaokaLog.setFromTxt(JSON.toJSONString(params));
		ordersHaokaLogService.insertOrdersHaokaLog(lhOrdersHaokaLog);

		if (StringUtils.isBlank(lhOrdersHaokaLog.getSign()) || StringUtils.isBlank(lhOrdersHaokaLog.getOuterId())) {
			updateOrdersHaokaLog(lhOrdersHaokaLog.getOrdersHaokaLogId(), Constants.GeneralIntType.TWO, "缺少必要条件");
			throw new ServiceException("缺少必要条件", HttpStatus.ERROR);
		}

		Map<String, String> formSign = new HashMap<>();
		formSign.put("outer_id", lhOrdersHaokaLog.getOuterId());
		formSign.put("plan_mobile_produced", lhOrdersHaokaLog.getPlanMobileProduced());
		formSign.put("status", lhOrdersHaokaLog.getState());
		String sign = null;
		try {
			sign = StringUtils.generateSignatureHaokaNotice(formSign, haokaUtil.getApiToken());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		if (!lhOrdersHaokaLog.getSign().equals(sign)) {
			updateOrdersHaokaLog(lhOrdersHaokaLog.getOrdersHaokaLogId(), Constants.GeneralIntType.TWO, "签名验证失败");
			throw new ServiceException("签名验证失败", HttpStatus.ERROR);
		}
		LhOrdersHaoka ordersHaoka = selectByOrderNumber(lhOrdersHaokaLog.getOuterId());
		if (ObjectUtil.isNull(ordersHaoka)) {
			updateOrdersHaokaLog(lhOrdersHaokaLog.getOrdersHaokaLogId(), Constants.GeneralIntType.TWO, "订单查询异常");
			throw new ServiceException("订单查询异常", HttpStatus.ERROR);
		}
		if (lhOrdersHaokaLog.getState().equals(ordersHaoka.getStatus())) {
			updateOrdersHaokaLog(lhOrdersHaokaLog.getOrdersHaokaLogId(), Constants.GeneralIntType.TWO, "订单不允许重复更新");
			throw new ServiceException("订单更新异常", HttpStatus.ERROR);
		}

		// 获取产品详情
		LhHaokaProduct lhHaokaProduct = haokaProductService.selectHaokaProductById(ordersHaoka.getProductId());
		if (ObjectUtil.isNull(lhHaokaProduct)) {
			updateOrdersHaokaLog(lhOrdersHaokaLog.getOrdersHaokaLogId(), Constants.GeneralIntType.TWO, "查询异常，产品数据不存在");
			throw new ServiceException("查询异常，产品数据不存在", HttpStatus.ERROR);
		}

		TransactionStatus transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition());
		try {

			// 更新订单
			LhOrdersHaoka order = new LhOrdersHaoka();
			order.setStatus(lhOrdersHaokaLog.getState());
			BigDecimal profit = BigDecimal.ZERO;
			order.setProfit(profit);
			order.setPlanMobileProduced(lhOrdersHaokaLog.getPlanMobileProduced());
			order.setStatus(params.getStatus());
			order.setAuditStatus(Constants.GeneralIntType.ONE);
			order.setReason(params.getReason());
			order.setIsActivated(lhOrdersHaokaLog.getIsActivated());
			order.setActivatedAt(StringUtils.isNotBlank(lhOrdersHaokaLog.getActivatedAt()) ? new Date(lhOrdersHaokaLog.getActivatedAt()) : null);
			order.setIsRecharged(lhOrdersHaokaLog.getIsRecharged());
			order.setRechargedAt(StringUtils.isNotBlank(lhOrdersHaokaLog.getRechargedAt()) ? new Date(lhOrdersHaokaLog.getRechargedAt()) : null);
			order.setTrackingCompany(lhOrdersHaokaLog.getTrackingCompany());
			order.setTrackingNumber(lhOrdersHaokaLog.getTrackingNumber());
			order.setUpdateTime(new Date());
			ordersHaokaMapper.updateById(order);

			LocalDate date = LocalDate.now();
			String year = date.getYear() + "";
			String yearMonth = StringUtils.join(date.getYear(), date.getMonthValue());
			String yearMonthDay = StringUtils.join(date.getYear(), date.getMonthValue(), date.getDayOfMonth());

			// 获取当前日期-周
			WeekFields weekFields = WeekFields.of(Locale.getDefault());
			Integer currentWeek = date.get(weekFields.weekOfWeekBasedYear());


			// 添加主订单
			LhOrdersPool ordersPool = new LhOrdersPool();
			ordersPool.setOrderNumber(ordersHaoka.getOrderNumber());
			ordersPool.setMemberId(ordersHaoka.getMemberId());
			ordersPool.setOrigin(Constants.ORDERS_ORIGIN_HAOKA);
			ordersPool.setOrderId(ordersHaoka.getOrderId());
			ordersPool.setRevenueType(Constants.ORDERS_REVENUE_TYPE_0);
			ordersPool.setProductName(ordersHaoka.getProductName());
			ordersPool.setProductLog(ordersHaoka.getProductLog());
			ordersPool.setYear(Integer.valueOf(year));
			ordersPool.setMonthly(Integer.valueOf(yearMonth));
			ordersPool.setWeekly(currentWeek);
			ordersPool.setDaily(Integer.valueOf(yearMonthDay));
			ordersPool.setMediaAmount(order.getProfit());
			ordersPool.setAmount(ordersHaoka.getProfit());
			ordersPool.setStatus(profit.compareTo(BigDecimal.ZERO) > 0 ? Constants.ORDERS_POOL_STATUS_1 : Constants.ORDERS_POOL_STATUS_0);
			ordersPool.setReason(params.getReason());
			ordersPoolService.insertOrdersPool(ordersPool);

			// 更新日志
			updateOrdersHaokaLog(lhOrdersHaokaLog.getOrdersHaokaLogId(), Constants.GeneralIntType.ONE, "正常");

			// 提交订单
			transactionManager.commit(transactionStatus);
		} catch (Exception e) {
			transactionManager.rollback(transactionStatus);
			updateOrdersHaokaLog(lhOrdersHaokaLog.getOrdersHaokaLogId(), Constants.GeneralIntType.TWO, "处理异常=>" + e.getMessage());
			throw new ServiceException("处理异常=>" + e.getMessage());
		}
	}

	private void updateOrdersHaokaLog(Long orderHaokaLogId, Integer status, String reason) {
		LhOrdersHaokaLog ordersHaokaLog = new LhOrdersHaokaLog();
		ordersHaokaLog.setOrdersHaokaLogId(orderHaokaLogId);
		ordersHaokaLog.setStatus(status);
		ordersHaokaLog.setReason(reason);
		ordersHaokaLogService.updateOrdersHaokaLog(ordersHaokaLog);
	}

	/**
	 * 根据订单编号查询订单
	 *
	 * @param orderNumber 订单编号
	 * @return com.lanhe.order.domain.LhOrdersHaoka
	 * @author zhanggl
	 * @date 2023/12/26
	 */
	private LhOrdersHaoka selectByOrderNumber(String orderNumber) {
		LambdaQueryWrapper<LhOrdersHaoka> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(LhOrdersHaoka::getOrderNumber, orderNumber);
		return ordersHaokaMapper.selectOne(queryWrapper);
	}

	/**
	 * 根据ID查询订单
	 *
	 * @param orderId id
	 * @return com.lanhe.order.domain.LhOrdersHaoka
	 * @author zhanggl
	 * @date 2024年01月04日14:42:56
	 */
	@Override
	public LhOrdersHaoka selectOrdersHaokaById(Long orderId) {
		LambdaQueryWrapper<LhOrdersHaoka> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(LhOrdersHaoka::getOrderId, orderId);
		return ordersHaokaMapper.selectOne(queryWrapper);
	}

	/**
	 * 审核返佣
	 *
	 * @param ordersHaoka 实体
	 * @return java.lang.Integer
	 * @author zhanggl
	 * @date 2024/1/4
	 */
	@Override
	public Integer auditOrdersHaokaById(LhOrdersHaoka ordersHaoka) {
		LhOrdersHaoka lhOrdersHaoka = selectOrdersHaokaById(ordersHaoka.getOrderId());
		if (ObjectUtil.isNull(lhOrdersHaoka)) {
			throw new ServiceException("查询异常", HttpStatus.ERROR);
		}
		if (!"1".equals(lhOrdersHaoka.getIsActivated()) && !"1".equals(lhOrdersHaoka.getIsRecharged())) {
			throw new ServiceException("不符合审核条件", HttpStatus.ERROR);
		}
		if (Constants.GeneralIntType.TWO.equals(lhOrdersHaoka.getAuditStatus())) {
			throw new ServiceException("订单已审核", HttpStatus.ERROR);
		}

		// 通过
		if (Constants.GeneralIntType.TWO.equals(ordersHaoka.getAuditStatus())) {

			LhOrdersPool lhOrdersPool = ordersPoolService.selectByOriginAndOrderId(Constants.ORDERS_ORIGIN_HAOKA, ordersHaoka.getOrderId());
			if (ObjectUtil.isNull(lhOrdersPool)) {
				throw new ServiceException("主订单数据不存在", HttpStatus.ERROR);
			}

			// 更新会员收益
			memberBaseService.updateMemberBenefits(lhOrdersPool);

			// 更新订单状态
			LhOrdersHaoka ordersHaokaNew = new LhOrdersHaoka();
			ordersHaokaNew.setOrderId(ordersHaoka.getOrderId());
			ordersHaokaNew.setAuditStatus(ordersHaoka.getAuditStatus());
			ordersHaokaNew.setReason(ordersHaoka.getReason());
			ordersHaokaMapper.updateById(ordersHaokaNew);
		} else {

			// 更新订单状态
			LhOrdersHaoka ordersHaokaNew = new LhOrdersHaoka();
			ordersHaokaNew.setOrderId(ordersHaoka.getOrderId());
			ordersHaokaNew.setAuditStatus(ordersHaoka.getAuditStatus());
			ordersHaokaNew.setReason(ordersHaoka.getReason());
			ordersHaokaMapper.updateById(ordersHaokaNew);
		}

		return 1;
	}
}


